/*
 * LibxmlParseXml.c
 *
 *  Created on: 2011-5-6
 *      Author: william nie
 */

#include <stdio.h>
#include <stdlib.h>
#include <libxml/parser.h>
#include <libxml/tree.h>
int main(int argc, char **argv) {
	xmlDocPtr pdoc = NULL;
	xmlNodePtr proot = NULL, curNode = NULL , childNode = NULL;

	// 打开 xml 文档，注意xmlReadFile的第一个参数是URL形式:file:///....
	xmlKeepBlanksDefault(0);
	pdoc = xmlReadFile("file:///.test.xml", "UTF-8", XML_PARSE_RECOVER);

	if (pdoc == NULL) {
		printf("OPEN FILE %s ERROR!\n", psfilename);
		fflush(stdin);
		getchar();
		exit(1);
	}

	// 获取 xml 文档对象的根节对象
	proot = xmlDocGetRootElement(pdoc);
	if (proot == NULL) {
		printf("ERROR: %s IS AN EMPTY DOC(WITH NO ROOT NODE)!\n", psfilename);
		fflush(stdin);
		getchar();
		exit(1);
	}

	/* 我使用上面程序创建的 xml 文档，它的根节点是“根节点”，这里比较是否     正确。*/
	if (xmlStrcmp(proot->name, BAD_CAST "root") != 0) {
		printf("ERROR DOC WITH ERROR ROOT NODE!");
		fflush(stdin);
		getchar();
		exit(1);
	}

	/* 如果打开的 xml 对象有 version 属性，那么就输出它的值。 */
	if (xmlHasProp(proot, BAD_CAST "version")) {
		xmlChar *szAttr = xmlGetProp(proot, BAD_CAST "version");
		printf("version: %s \nroot node:%s\n", szAttr, proot->name);
	} else {
		printf(" xml doc with no version attribute\n");
	}

	curNode = proot->xmlChildrenNode;
	char n = 0;
	char m = 0;
	while (curNode != NULL) {

		printf("Child Node%d: %s\n", n++, curNode->name);

		if(curNode->children!=NULL && xmlStrcmp(curNode->children->name,BAD_CAST "text")){
			childNode = curNode->children;
			m = 1;
			while(childNode != NULL){
				printf("\tChild Node%d: %s\n", m++,childNode->children->content);
				childNode = childNode->next;
			}
		}



		curNode = curNode->next;
	}

	fflush(stdin);
	getchar();

	/* 关闭和清理 */
	xmlFreeDoc(pdoc);
	xmlCleanupParser();

	return 0;
}
